import os
import traceback
from xunkemgmt_client.tool.slack_noti import send_to_slack
from coin.base.mail_util import send_mail, send_mail_with_attachments
from absl import app, flags


def notice_slack(report, slack, subject, context):
  if slack is None:
    return
  with open(report) as f:
    send_to_slack(f.read(), slack, 'file', subject)
  send_to_slack(context, slack, 'msg', subject)


def send_to_mail(report, from_mail, to_mail, subject, context):
  if to_mail is None:
    return
  try:
    send_mail_with_attachments("", from_mail, to_mail, subject, context, report)
  except:
    traceback.print_exc()


def create_git_pr(token_file_path, branch_name, message, repo="prestolabs/coin"):
  if not os.path.isfile(token_file_path):                                                            
    print('access token is required for create PR')                                                  
    return False, ""                                                                                 
  with open(token_file_path) as file:                                                               
    token = file.read().replace('\n', '')
  try:
    from github import Github
    g = Github(token)
    update = g.get_repo(repo)
    pr = update.create_pull(branch_name, message, 'master', branch_name)
    print(pr.html_url)
    return True, pr.html_url
  except ImportError:
    print('GitHub library is not installed. Run `pip install PyGithub`')
    return False, ""


def main(argv):
  if flags.FLAGS.branch is None:
    print("Error: no branch given")
    return
  ret, pr_url = create_git_pr(flags.FLAGS.token_file_path,
                              flags.FLAGS.branch,
                              "update the pi for multiple exchanges")
  if ret:
    context = "please review the PR of the pi update. %s" % pr_url
  else:
    context = "failed to create PR for the branch %s, please check" % flags.FLAGS.branch
  notice_slack(flags.FLAGS.report,
               flags.FLAGS.slack,
               flags.FLAGS.subject,
               context)
  send_to_mail(flags.FLAGS.report,
               flags.FLAGS.from_mail,
               flags.FLAGS.to_mail,
               flags.FLAGS.subject,
               context)


if __name__ == '__main__':
  flags.DEFINE_string('subject', '', 'email subject')
  flags.DEFINE_string('context', '', 'email context')
  flags.DEFINE_string('report', '', 'report file')
  flags.DEFINE_string('slack', None, 'slack_channel')
  flags.DEFINE_string('to_mail', None, 'to email address')
  flags.DEFINE_string('from_mail', 'no-reply@joomo.io', 'from email address')
  flags.DEFINE_string('branch', None, 'branch name')
  flags.DEFINE_string('token_file_path', '', 'token file path')
  app.run(main)
